package service

import (
	"errors"
	"gorm.io/gorm"
	"server/client/db"
	"server/model"
	"server/model/request"
	"server/utils"
)

func Register(u model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser
	if !errors.Is(db.DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return errors.New("用户名已注册"), userInter
	}

	u.UUID = utils.GenUUID()

	u.Password = utils.MD5V([]byte(u.Password))
	if err := db.DB.Create(&u).Error; err != nil {
		return err, nil
	}
	return nil, &u

}
func Login(u *model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser

	u.Password = utils.MD5V([]byte(u.Password))
	// 预先查询role信息在查询user信息
	// 根据查询的salt信息匹配传入的password是否一致
	err = db.DB.Where("username = ? AND password = ?", u.Username, u.Password).Preload("Role").First(&user).Error

	return err, &user
}

func GetUserInfoList(info request.PageInfo) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	dbc := db.DB.Model(&model.SysUser{})
	var userList []model.SysUser
	err = dbc.Count(&total).Error
	err = dbc.Limit(limit).Offset(offset).Preload("Role").Find(&userList).Error
	return err, userList, total
}

func DeleteUser(id string) (err error) {
	var user model.SysUser
	err = db.DB.Where("uuid = ?", id).Delete(&user).Error
	return err
}

func ChangePassword(u *model.SysUser, newPassword string) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = db.DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	return err, u
}

func ChangeUserRole(uuid string, roleId string) (err error) {
	err = db.DB.Where("uuid = ?", uuid).First(&model.SysUser{}).Update("role_id", roleId).Error
	return err
}


func FindUserById(id int) (err error, user *model.SysUser) {
	var u model.SysUser
	err = db.DB.Where("`id` = ?", id).First(&u).Error
	return err, &u
}

func FindUserByUuid(uuid string) (err error, user *model.SysUser) {
	var u model.SysUser
	if err = db.DB.Where("`uuid` = ?", uuid).Preload("Role").First(&u).Error; err != nil {
		return errors.New("用户不存在"), &u
	}
	return nil, &u
}
